package com.aygxy.carproject.security;

import com.aygxy.carproject.mapper.UserMapper;
import com.aygxy.carproject.pojo.user.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security自动调用loadUserByUsername()方法获取用户名为【{}】的用户详情……", s);

        UserLoginInfoVO loginInfoByUsername = userMapper.getLoginInfoByUsername(s);
        log.debug("从数据库中查询到的用户信息：{}", loginInfoByUsername);
        if (loginInfoByUsername == null) {
            String message = "登录失败，用户名不存在！";
            log.warn(message);
            throw new BadCredentialsException(message);
        }

        List<String> permissions = loginInfoByUsername.getPermissions();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }

        UserDetail userDetails = new UserDetail(
                loginInfoByUsername.getUsername(), loginInfoByUsername.getPassword(),
                loginInfoByUsername.getStatus() == 1, authorities);
        userDetails.setId(loginInfoByUsername.getId());

//        UserDetails userDetails = User.builder()
//                .username(loginInfoByUsername.getUsername())
//                .password(loginInfoByUsername.getPassword())
//                .accountExpired(false) // 账号是否已过期
//                .accountLocked(false) // 账号是否已锁定
//                .credentialsExpired(false) // 凭证是否已过期
//                .disabled(loginInfoByUsername.getStatus() == 0) // 账号是否已禁用
//                .authorities("临时设置的权限，避免报错，暂无意义") // 权限，【注意】必须调用此方法表示此用户具有哪些权限
//                .build();
        log.debug("即将向Spring Security框架返回UserDetails对象：{}", userDetails);
        return userDetails;
    }

}
